import { memo, useCallback, useEffect, useState } from 'react';
import { Position, useReactFlow, Node } from '@xyflow/react';
import { Card, Form, Input, Modal, Select, Spin } from 'antd';
import Subtitle from '../../components/Subtitle';
import useSelectBorder from '../../store/useSceneData';
import CustomHandle from '../CustomHandle';
import { Loading3QuartersOutlined } from '@ant-design/icons';
import NodeOperation from '../../components/NodeOperation';
import LexicalEdit from '../../components/LexicalEdit';
import { lexicalEditParse } from '../../utils/utils';
import useInitVariable from '@/hooks/useInitVariable';


/**
 * 流程节点
 * @param param0 
 * @returns 
 */
const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 },
};

function TextUpdaterNode({ id, data }: Node) {
  const { setNodes, setCenter } = useReactFlow();
  const { select, setSelectId, debug, setDeBug } = useSelectBorder()
  // 输出结果满足条件
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [form] = Form.useForm();
  const { Option } = Select;
  const [url, setUrl] = useState<string>('')
  const { initSetVariable } = useInitVariable()

  const handleFocus = () => {
    setSelectId(id);
    setDeBug(false)
  };

  const onChange = useCallback(() => {
    setNodes((nodes) => {
      data = form.getFieldsValue()
      const node = nodes.find(node => node.id == id)
      node.data.urlAtom = data.urlAtom
      node.data.url = lexicalEditParse(data.urlAtom) || ""
      setUrl(node.data.url as string)
      node.data.type = data.type

      node.data.params = lexicalEditParse(data.paramsAtom) || "{}"
      node.data.heads = lexicalEditParse(data.headsAtom) || "{}"
      node.data.body = lexicalEditParse(data.bodyAtom) || "{}"

      node.data.paramsAtom = data.paramsAtom
      node.data.headsAtom = data.headsAtom
      node.data.bodyAtom = data.bodyAtom

      return [...nodes];
    })
  }, []);

  useEffect(() => {
    setNodes((nodes) => {
      const node = nodes.find(node => node.id == id)
      node.data.url = data.url
      setUrl(data.url as string)
      node.data.type = data.type

      node.data.headsAtom = data.headsAtom
      node.data.paramsAtom = data.paramsAtom
      node.data.bodyAtom = data.bodyAtom
      node.data.urlAtom = data.urlAtom

      return [...nodes];
    })
    form.setFieldsValue(data)
  }, [data])

  useEffect(() => {
    initSetVariable(data.title as string || "HTTP", id)
  }, [])

  useEffect(() => {
    if (select[id] && debug) {
      setNodes((nodes) => {
        const node = nodes.find(node => node.id == id)
        setCenter(node.position.x + 200, node.position.y, { zoom: 1, duration: 500 })
        return [...nodes];
      })
    }
  }, [select[id]])

  return (
    <NodeOperation nodeId={id} onClick={() => setIsModalOpen(true)}>
      <Card
        title={<div className='flex'>
          <Subtitle imgUrl='img/http.png' title={data.title as string || 'HTTP'} id={id}
            onBlur={(title) => initSetVariable(title, id)} />
          {select[id] && debug && <Spin indicator={<Loading3QuartersOutlined spin />} className='mt-[6px] ml-2' />}
        </div>}
        style={{
          outline: select[id] ? "2px solid #145FF0" : "none",
          position: 'relative',
          width: 304,
        }}
        onClick={handleFocus}
        tabIndex={0}
      >
        <CustomHandle count={2} type="target" position={Position.Left} id="httpStart" style={{ top: 74 }} />
        <Modal
          title={<span>{data.title as string || 'HTTP请求'}</span>}
          open={isModalOpen}
          footer={false}
          destroyOnClose={true}
          onCancel={() => {
            onChange()
            setIsModalOpen(false)
          }}>
          <Form
            {...layout}
            form={form}
            // className='mt-6'
            name="control-hooks"
          >
            <Form.Item name="urlAtom" label="请求路径" rules={[{ required: true }]}>
              <LexicalEdit title='路径' height={50} />
            </Form.Item>
            <Form.Item name="type" label="请求类型" rules={[{ required: true }]}>
              <Select
                placeholder="请求类型"
              >
                <Option value="GET">GET</Option>
                <Option value="POST">POST</Option>
                <Option value="DELETE">DELETE</Option>
                <Option value="PUT">PUT</Option>
              </Select>
            </Form.Item>
            <Form.Item name="headsAtom" label="请求头" rules={[{ required: true }]}>
              <LexicalEdit height={100} />
            </Form.Item>
            <Form.Item name="paramsAtom" label="请求参数" rules={[{ required: true }]}>
              <LexicalEdit height={100} />
            </Form.Item>
            <Form.Item name="bodyAtom" label="请求体" rules={[{ required: true }]}>
              <LexicalEdit height={100} />
            </Form.Item>
          </Form>
        </Modal>
        {url && <div className='bg-[#F3F4F7] w-[254px] rounded-lg text-[#667085] break-all'>{url}</div>}
        <CustomHandle count={1} type="source" position={Position.Right} id="httpEnd" style={{ top: 74 }} />
      </Card>
    </NodeOperation>
  );
}

export default memo(TextUpdaterNode)